import xlrd

from django.contrib.auth.models import User
from models import Class

def create_stu(id, name, cls_name):
    is_success = True
    info = 'Success!'
    if id and name and cls_name:
        try:
            cls = Class.objects.get(name=cls_name)
            try:
                stu = User.objects.get(username=id)
                clses = stu.cls.all()
                if len(clses):
                    if cls.name != clses[0].name:
                        is_success = False
                        info = "%s--%s is already in %s!" % (stu.username, stu.first_name, clses[0].name)
                    else:
                        info = "%s--%s--%s already exist!" % (stu.username, stu.first_name, cls.name)
                else:
                    cls.students.add(stu)
                    cls.save()
            except User.DoesNotExist:
                stu = User.objects.create(username=id, password=id, first_name=name)
                stu.save()
                cls.students.add(stu)
                cls.save()
        except Class.DoesNotExist:
            try:
                stu = User.objects.get(username=id)
                clses = stu.cls.all()
                if len(clses):
                    if cls_name == clses[0].name:
                        cls = clses[0]
                    else:
                        is_success = False
                        info = "%s--%s is already in %s!" % (stu.username, stu.first_name, clses[0].name)
                else:
                    cls = Class(name=cls_name)
                    cls.save()
                    cls.students.add(stu)
                    cls.save()
            except User.DoesNotExist:
                stu = User.objects.create(username=id, password=id, first_name=name)
                stu.save()
                cls = Class(name=cls_name)
                cls.save()
                cls.students.add(stu)
                cls.save()

    else:
        is_success = False
        info = 'invalid info!'
    res = {'id': id, 'name':name, 'cls_name':cls_name, 'is_success':is_success, 'info':info}
    return res 

def import_stu_from_file(stu_file):
#    try:
    result_list = []
    bk = xlrd.open_workbook(file_contents=stu_file.read())
    sh = bk.sheet_by_index(0)
    nrows = sh.nrows
    for i in range(0, nrows):
        id = sh.cell_value(i, 0)
        name = sh.cell_value(i, 1)
        cls_name = sh.cell_value(i, 2)
        res = create_stu(id, name, cls_name)
        result_list.append(res)
    return result_list
#    except:
#        raise "read file failed!"

def import_stu_from_text(stu_text):
    result_list = []
    rows = stu_text.split('\r\n')
    for row in rows:
        elem = row.split('\t')
        for i in range(len(elem), 3):
            elem.append('')
        res = create_stu(elem[0], elem[1], elem[2])
        result_list.append(res)
    return result_list
